<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .slider-bar {
            position: absolute;
            height: 130px;
            width: 45px;
            margin-left: 600px;
            background-color: pink;
            left: 50%;
            top: 400px;
        }
        .w {
            width: 1200px;
            margin: 10px auto;
        }
        .header {
            height: 200px;
            background-color: purple;
        }
        .banner {
            height: 500px;
            background-color: skyblue;
        }
        .main {
            height: 1000px;
            background-color: yellowgreen;
        }
        span {
            display: none;
            position: absolute;
            bottom:0;
        }
    </style>
</head>
<body>
    <div class="slider-bar">
        <span class="goBack">返回顶部</span>
    </div>
    <div class="header w">头部区域</div>
    <div class="banner w">banner区域</div>
    <div class="main w"></div>
    <script>
        // 1. 获取元素
        var sliderbar = document.querySelector('.slider-bar')
        var banner = document.querySelector('.banner')
        console.log(banner.offsetTop);
        // banner.offestTop 就是被卷去头部的大小 一定要写到滚动的外面
        var bannerTop = banner.offsetTop
        // 当我们的侧边栏固定定位之后应该变化的数值
        var sliderbarTop = sliderbar.offsetTop - bannerTop
        // 获取main主体元素
        var main = document.querySelector('.main')
        var goBack = document.querySelector('.goBack')
        var mainTop = main.offsetTop
        // 2. 页面滚动事件 scroll
        document.addEventListener('scroll', function(){
            // 页面被卷去的头部
            console.log(window.pageYOffset); 
            // 3. 当我们的页面被卷去的头部大于大于222 此时 侧边栏就要改为固定定位
            if (window.pageYOffset >= bannerTop){
                sliderbar.style.position = 'fixed'
                sliderbar.style.top = sliderbarTop + 'px'

            }else {
                sliderbar.style.position = 'absolute'
                sliderbar.style.top = '400px'
            }
            if (window.pageYOffset >= mainTop){
                goBack.style.display = 'block'

            }else {
                goBack.style.display = 'none'

            }
        })
    </script>
</body>
</html>